package com.example.core.exception;

import com.example.core.annotation.HasPerm;
import com.example.model.response.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.model.constants.CodeConstants.VALIDATE_ERROR;

public class GlobalExceptionHandler {

    @ExceptionHandler(HotelException.class)
    protected ResponseEntity<Result> handleHotelException(HotelException e) {
        HttpStatus httpStatus;
        try {
            httpStatus = HttpStatus.valueOf(e.getCode());
        } catch (IllegalArgumentException ex) {
            // 如果错误码无效，默认使用500
            httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return new ResponseEntity<>(
                Result.error(e.getCode(), e.getMessage()),
                httpStatus
        );
//        return ResponseEntity.status(e.getCode()).body(Result.error(e.getCode(), e.getMessage()));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    protected Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();  //获取绑定数据
        Map<String, String> errorMap = new HashMap<>();  //使用Map存储错误信息 name-msg
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();  //获取错误信息
        for (FieldError fieldError : fieldErrors) {
            String field = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            errorMap.put(field , message);
        }
        return Result.error(VALIDATE_ERROR , "参数校验失败" , errorMap);
    }

}
